package org.secangkirkopipanas.gxtcore.server.init;

import java.util.Date;

import org.secangkirkopipanas.gxtcore.server.dao.impl.SystemBusinessUnitDAO;
import org.secangkirkopipanas.gxtcore.server.dao.impl.SystemGroupDAO;
import org.secangkirkopipanas.gxtcore.server.dao.impl.SystemUserDAO;
import org.secangkirkopipanas.gxtcore.server.domain.SystemBusinessUnit;
import org.secangkirkopipanas.gxtcore.server.domain.SystemGroup;
import org.secangkirkopipanas.gxtcore.server.domain.SystemUser;
import org.secangkirkopipanas.gxtcore.server.util.Helper;

public class DBInit {

	public static void setupSystemBusinessUnit() throws Exception {
		SystemBusinessUnitDAO dao = new SystemBusinessUnitDAO();
		dao.setSessionFactory(Helper.getHibernateSession().getSessionFactory());
		dao.add(new SystemBusinessUnit("IT Dept"));
	}

	public static void setupSystemGroup() throws Exception {
		SystemBusinessUnitDAO dao = new SystemBusinessUnitDAO();
		dao.setSessionFactory(Helper.getHibernateSession().getSessionFactory());
		SystemGroup systemGroup1 = new SystemGroup("Group 1", dao
				.get("IT Dept"));

		SystemGroupDAO dao2 = new SystemGroupDAO();
		dao2
				.setSessionFactory(Helper.getHibernateSession()
						.getSessionFactory());
		dao2.add(systemGroup1);
	}

	public static void setupSystemUser() throws Exception {
		SystemGroupDAO dao = new SystemGroupDAO();
		dao.setSessionFactory(Helper.getHibernateSession().getSessionFactory());
		SystemGroup systemGroup1 = dao.get("Group 1");
		SystemUser systemUser1 = new SystemUser("user1", "user1", "Lilik",
				"Haryanto", systemGroup1, "Mr. ", "Jakarta", "02199000662",
				new Date(), "192.168.1.1", false);

		SystemUserDAO dao2 = new SystemUserDAO();
		dao2
				.setSessionFactory(Helper.getHibernateSession()
						.getSessionFactory());
		dao2.add(systemUser1);
	}

	public static void main(String[] args) {
		try {
			System.out
					.print("Installing database for GXTCore will take some minutes, please wait...");

			/** Getting the Session Factory and session */

			Helper.getHibernateSession().beginTransaction();

			DBInit.setupSystemBusinessUnit();
			DBInit.setupSystemGroup();
			DBInit.setupSystemUser();

			Helper.getHibernateSession().getTransaction().commit();

			/** Closing Session */
			Helper.getHibernateSession().close();

			System.out.println();
			System.out
					.println("Database for GXTCore was installed successfully");

		} catch (Exception e) {
			if (Helper.getHibernateSession() != null)
				Helper.getHibernateSession().getTransaction().rollback();
			e.printStackTrace();
		}

	}
}